package com.bes.bessdk.utils;

import android.content.Context;
import android.os.Environment;
import android.os.HandlerThread;
import android.util.Log;


import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class FileUtils {

    /**
     * 删除目录
     *
     * @param dirPath 目录路径
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteDir(String dirPath) {
        return deleteDir(getFileByPath(dirPath));
    }

    /**
     * 删除文件
     *
     * @param file 文件
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteFile(File file) {
        return file != null && (!file.exists() || file.isFile() && file.delete());
    }
    /**
     * 判断目录是否存在，不存在则判断是否创建成功
     *
     * @param dirPath 目录路径
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(String dirPath) {
        return createOrExistsDir(getFileByPath(dirPath));
    }
    /**
     * 获取目录下所有文件
     *
     * @param dirPath     目录路径
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(String dirPath, boolean isRecursive) {
        return listFilesInDir(getFileByPath(dirPath), isRecursive);
    }
    /**
     * 获取目录下所有文件包括子目录
     *
     * @param dirPath 目录路径
     * @return 文件链表
     */
    public static List<File> listFilesInDir(String dirPath) {
        return listFilesInDir(getFileByPath(dirPath));
    }

    /**
     * 获取目录下所有文件包括子目录
     *
     * @param dir 目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(File dir) {
        if (!isDir(dir)) return null;
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                list.add(file);
                if (file.isDirectory()) {
                    list.addAll(listFilesInDir(file));
                }
            }
        }
        return list;
    }
    /**
     * 判断文件是否存在
     *
     * @param file 文件
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public static boolean isFileExists(File file) {
        return file != null && file.exists();
    }
    /**
     * 判断是否是目录
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isDir(File file) {
        return isFileExists(file) && file.isDirectory();
    }

    /**
     * 获取目录下所有文件
     *
     * @param dir         目录
     * @param isRecursive 是否递归进子目录
     * @return 文件链表
     */
    public static List<File> listFilesInDir(File dir, boolean isRecursive) {
        if (!isDir(dir)) return null;
        if (isRecursive) return listFilesInDir(dir);
        List<File> list = new ArrayList<>();
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            Collections.addAll(list, files);
        }
        return list;
    }
    /**
     * 判断目录是否存在，不存在则判断是否创建成功
     *
     * @param file 文件
     * @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
     */
    public static boolean createOrExistsDir(File file) {
        // 如果存在，是目录则返回true，是文件则返回false，不存在则返回是否创建成功
        return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
    }
    /**
     * 删除目录
     *
     * @param dir 目录
     * @return {@code true}: 删除成功<br>{@code false}: 删除失败
     */
    public static boolean deleteDir(File dir) {
        if (dir == null) return false;
        // 目录不存在返回true
        if (!dir.exists()) return true;
        // 不是目录返回false
        if (!dir.isDirectory()) return false;
        // 现在文件存在且是文件夹
        File[] files = dir.listFiles();
        if (files != null && files.length != 0) {
            for (File file : files) {
                if (file.isFile()) {
                    if (!deleteFile(file)) return false;
                } else if (file.isDirectory()) {
                    if (!deleteDir(file)) return false;
                }
            }
        }
        return dir.delete();
    }

    public static File getFileByPath(String filePath) {
        return new File(filePath);
    }

    private static String mPath	= Environment.getExternalStorageDirectory() + "/";
    public static String OTA_FILE_NAME = "ota.txt";
    private Context mContext;
    public static String OTA_STATIC = "ota_static";//ota 统计记表
    public FileUtils(Context context) {
        mContext = context;
    }

    public String getFilesDir(String path, String folder) {
        String dirPath = mContext.getExternalFilesDir("").getAbsolutePath() + "/" + folder + "/";
        createFolder(dirPath);
        String filePath = dirPath + path;
        return filePath;
    }

    public void initBinFile() {
        String path = mContext.getExternalFilesDir("").getAbsolutePath();
        String filePath = path + "/bin";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public String getOtaFilePath() {
        String path = mContext.getExternalFilesDir("").getAbsolutePath();
        String filePath = path + "/bin";
        return filePath;
    }

    public String[] getOtaBinFileNames() {
        String path = mContext.getExternalFilesDir("").getAbsolutePath();
        String filePath = path + "/bin";
        File fatherFile = new File(filePath);
        File[] files = fatherFile.listFiles();
        if (files != null && files.length > 0) {
            String[] fileNames = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                fileNames[i] = files[i].getName();
            }
            return fileNames;
        }
        return new String[0];
    }

    public void saveBytesToFile(String path, String folder, byte[] data) {
        String filePath = getFilesDir(path, folder);
        File file = new File(filePath);
        BufferedOutputStream outStream = null;
        try {
            outStream = new BufferedOutputStream(new FileOutputStream(file, true));
            outStream.write(data);
            outStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void createFolder(String path) {
        File fileDir = new File(path);
        boolean hasDir = fileDir.exists();
        if (!hasDir) {
            fileDir.mkdirs();// 这里创建的是目录
        }
    }

    public static void writebytetofile(String path, byte[] data) {
        File file = new File(path);
        BufferedOutputStream outStream = null;
        try {
            outStream = new BufferedOutputStream(new FileOutputStream(file, true));
            outStream.write(data);
            outStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void writeTOfileAndActiveClear(String filename, String context)
    {
        Log.i("TAG", "writeTOfileAndActiveClear: ------" + context);
        String pkgName= "bb.lanxing"; //"com.bes.besall"
        String path = getFolderPath()+"Android/" + "data/" + pkgName + "/" + "files/";
        isExist(path);
        path = path+"OTA/";
        isExist(path);
        path = path + filename + ".txt";
        File file = new File(path);
        try
        {
            if (!file.exists())
            {
                file.createNewFile();
            }
            FileInputStream fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
            /**
             * 当文件大小大于80MByte时，主动删除
             */
            if (size >= 80000000)
            {
                file.delete();
                return;
            }

            FileOutputStream stream = new FileOutputStream(file, true);
            String temp = context + "\n";
            byte[] buf = temp.getBytes();
            stream.write(buf);
            stream.close();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static void writeToFile(String filePath, String context) {

        File file = new File(filePath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file, true));
            bw.write(context);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void writeTOFile(Object obj, String folderName, String fileName, String fileType)
    {
        Log.i("TAG", "writeTOFile: " + obj);
        String path = getFolderPath() + "Android/" + "data/" + "com.bes.besall" + "/" + "files/";
        isExist(path);
        path = path + folderName + "/";
        isExist(path);
        path = path + fileName + "." + fileType;
        File file = new File(path);
        Log.i("TAG", "writeTOFile: path" + path);
        try
        {
            if (!file.exists())
            {
                file.createNewFile();
            }
            FileInputStream fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
            /**
             * 当文件大小大于80MByte时，主动删除
             */
            if (size >= 80000000)
            {
                file.delete();
                return;
            }

            FileOutputStream stream = new FileOutputStream(file, true);

            if (obj.getClass() == String.class) {
                String temp = obj + "\n";
                byte[] buf = temp.getBytes();
                stream.write(buf);
                stream.close();
            } else if (obj.getClass() == byte[].class) {
                byte[] buf = (byte[]) obj;
                stream.write(buf);
                stream.close();
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String getFolderPath()
    {
        String pathString = mPath;
        isExist(pathString);
        pathString += "/";
        return pathString;
    }

    public static void isExist(String path)
    {
        File file = new File(path);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists())
        {
            synchronized (FileUtils.class)
            {
                file.mkdirs();
            }
        }
    }

    public void HandleAnalyseFile(String info, String folderName, String fileName,String path)
    {
//        String filePath = getFolderPath()+"Android/" + "data/" + "com.bes.besall/" + "files/";
//        isExist(filePath);
//        filePath = filePath + folderName +"/";
//        isExist(filePath);
//        filePath = filePath + fileName;
//        isExist(filePath);
        String filePath = getFilesDir(path, folderName);
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                FileOutputStream stream = new FileOutputStream(filePath, true);
                //String title = "Time,LEFT_AGC_1, LEFT_RSSI_1,LEFT_AGC_2, LEFT_RSSI_2,LEFT_AGC_3, LEFT_RSSI_3,LEFT_RxGAIN,LEFT_TxGAIN,RIGHT_AGC_1, RIGHT_RSSI_1,RIGHT_AGC_2, RIGHT_RSSI_2,RIGHT_AGC_3, RIGHT_RSSI_3,RIGHT_RxGAIN,RIGHT_TxGAIN"+ "\n";

                String title = "TIME,LEFT_PHONE_AGC, LEFT_PHONE_RSSI,LEFT_PHONE_MAX_RSSI,LEFT_PHONE_MIN_RSSI,LEFT_TWS_ARC,LEFT_TWS_RSSI,LEFT_TWS_MAX_RSSI,LEFT_TWS_MIN_RSSI,raw_rssi.ser,fa_idx_left,MIRROR_LEFT_PHONE_AGC,MIRROR_LEFT_PHONE_RSSI,MIRROR_LEFT_PHONE_MAX_RSSI,MIRROR_LEFT_PHONE_MIN_RSSI,RIGHT_PHONE_AGC,RIGHT_PHONE_RSSI,RIGHT_PHONE_MAX_RSSI,RIGHT_PHONE_MIN_RSSI,RIGHT_TWS_AGC,RIGHT_TWS_RSSI,RIGHT_TWS_MAX_RSSI,RIGHT_TWS_MIN_RSSI,peer_raw_rssi.ser,fa_idx_right,MIRROR_RIGHT_PHONE_AGC,MIRROR_RIGHT_PHONE_RSSI,MIRROR_RIGHT_PHONE_MAX_RSSI,MIRROR_RIGHT_PHONE_MIN_RSSI,CURRENT_ROLE"+"\n";
//                String title = "TIME,LEFT_PHONE_AGC, LEFT_PHONE_RSSI,LEFT_PHONE_MAX_RSSI,LEFT_PHONE_MIN_RSSI,LEFT_TWS_ARC,LEFT_TWS_RSSI,LEFT_TWS_MAX_RSSI,LEFT_TWS_MIN_RSSI,raw_rssi.ser,RIGHT_PHONE_AGC,RIGHT_PHONE_RSSI,RIGHT_PHONE_MAX_RSSI,RIGHT_PHONE_MIN_RSSI,RIGHT_TWS_AGC,RIGHT_TWS_RSSI,RIGHT_TWS_MAX_RSSI,RIGHT_TWS_MIN_RSSI,peer_raw_rssi.ser,CRRENT_ROLE,extra_data "+"\n";


                stream.write(title.getBytes("gbk"));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream stream = new FileOutputStream(filePath, true);
            stream.write(info.getBytes("gbk"));
            stream.flush();
            stream.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public void RssiextendAnalyseFile(String info, String folderName, String fileName,String path)
    {
//        String filePath = getFolderPath()+"Android/" + "data/" + "com.bes.besall/" + "files/";
//        isExist(filePath);
//        filePath = filePath + folderName +"/";
//        isExist(filePath);
//        filePath = filePath + fileName;
//        isExist(filePath);
        String filePath = getFilesDir(path, folderName);
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                FileOutputStream stream = new FileOutputStream(filePath, true);

                String title = "TIME,LEFT_PHONE_AGC, LEFT_PHONE_RSSI,LEFT_PHONE_MAX_RSSI,LEFT_PHONE_MIN_RSSI,LEFT_TWS_ARC,LEFT_TWS_RSSI,LEFT_TWS_MAX_RSSI,LEFT_TWS_MIN_RSSI,raw_rssi.ser,RIGHT_PHONE_AGC,RIGHT_PHONE_RSSI,RIGHT_PHONE_MAX_RSSI,RIGHT_PHONE_MIN_RSSI,RIGHT_TWS_AGC,RIGHT_TWS_RSSI,RIGHT_TWS_MAX_RSSI,RIGHT_TWS_MIN_RSSI,peer_raw_rssi.ser,CRRENT_ROLE,extra_data "+"\n";


                stream.write(title.getBytes("gbk"));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream stream = new FileOutputStream(filePath, true);
            stream.write(info.getBytes("gbk"));
            stream.flush();
            stream.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public void HandleFileReport(String info, String folderName, String fileName,String path)
    {
//        String filePath = getFolderPath()+"Android/" + "data/" + "com.bes.besall/" + "files/";
//        isExist(filePath);
//        filePath = filePath + folderName +"/";
//        isExist(filePath);
//        filePath = filePath + fileName;
//        isExist(filePath);
        String filePath = getFilesDir(path, folderName);
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream stream = new FileOutputStream(filePath, true);
            Log.e("info = ",info);
            stream.write(info.getBytes("gbk"));
            stream.flush();
            stream.close();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }

    }

    public static void writeArrayListTOFile(ArrayList tArrayList, String folderName, String fileName, String fileType)
    {
        String path = getFolderPath()+"Android/" + "data/" + "com.bes.besall" + "/" + "files/";
        isExist(path);
        path = path + folderName +"/";
        isExist(path);
        path = path + fileName;
        File file = new File(path);
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);  //新建一个内容为空的文件
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(tArrayList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (objectOutputStream != null) {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void writeFlashContentfiles(String path, String folder, String info)
    {
        String filePath = getFilesDir(path, folder);
        File file = new File(filePath);
        try
        {
            if (!file.exists())
            {
                file.createNewFile();
            }
            FileInputStream fis = new FileInputStream(file);
            long size = fis.available();
            fis.close();
        }
        catch (IOException e)
        {
            Log.e("ex",e.getMessage().toString());
        }

    }

    public static String cutLastSegmentOfPath(String path) {
        return path.substring(0, path.lastIndexOf("/"));
    }


}
